#coding=utf-8
import datetime
from time import sleep
import stutils
stutils.set_django_environ()
from djstock.shstock.models import *
from scraper import NoPriceTodayError,NoDealError

from average import vlist    
for s in Share.objects.order_by('code'):
    if not s.has_tdprice():
        try:
            s.tdprice2db()
        except NoPriceTodayError,e:
            print s,e
        else:
            e = s.exday_set.latest('date')
            print s, e.date, e.price.end, e.price.change        

print "Price data from sina is ok!"
sleep(10)

'''
for s in Share.objects.all():
    e = s.exday_today()
    if e and not e.has_deal():
        try:
            e.deal2db()
        except NoDealError, e:
            print e
    print s


#average
from config import avg_ns

def apn(e, n):
    
    pre = e.pre
    if not pre:return None
    
    pre_apn = getattr( pre.avgprice, 'ap%s'%str(n), None)
    if pre_apn:
        pren = e.prenday(n)
        pren_end = pren.price.end
        
        end = e.price.end
        return stutils.float2dec( (pre_apn * n + end - pren_end)/ n , 2) 
    else:
        es = vlist(e.share, 'end')
        print n, "average price."
        print len(es)
        if len(es) == n:
            return stutils.float2dec( sum(es)/n )
        return None

for s in Share.objects.order_by('code'):              
    e = s.exday_today()
    if e:
        ap = AveragePrice(exday=e)
        for n in avg_ns:
            data = apn(e, n):
            if data:setattr(ap, 'ap%s'%str(n), data)
        ap.save()
    print s
    
print "均线ok"
'''

        
    
